<template>
  <div class="spotCheck-content-tabs">
    <div class="spotCheck-content-tabs-content">
      <el-scrollbar style="height: 70px">
        <div
          :class="
            params.sorgSpotCheckPlanId === it.sorgSpotCheckPlanId
              ? 'spotCheck-content-tabs-content-title spotCheck-content-tabs-content-ac'
              : 'spotCheck-content-tabs-content-title'
          "
          v-for="it in latestSixData"
          @click="setPlan(it.sorgSpotCheckPlanId)"
        >
          {{ it.planName }}
        </div>
      </el-scrollbar>
    </div>
    <div class="spotCheck-content-tabs-rig">
      <img
        src="@/assets/imgs/spotCheck/menu1.png"
        @click="setVisible"
        v-if="visible"
      />
      <img src="@/assets/imgs/spotCheck/menu.png" @click="setVisible" v-else />
      <el-button
        type="primary"
        @click="spotCheckPlanManagement"
        v-if="$checkAuth('qualifiedSpotChecksSpotCheckPlanManagement')"
      >
        <template #icon>
          <img
            src="@/assets/imgs/spotCheck/icon/c1.svg"
            alt="icon"
            class="btn-icon"
          />
        </template>
        抽查计划管理
      </el-button>
    </div>
    <TabList
      v-model:visible="visible"
      v-model="params.sorgSpotCheckPlanId"
      :planList="planList"
    />
  </div>
  <div class="spotCheck-content">
    <!--筛选-->
    <div class="spotCheck-content-search">
      <el-form
        ref="ruleFormRef"
        :model="form"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-row :gutter="40" style="width: 100%">
          <el-col :span="6">
            <el-form-item label="检查对象" prop="objectName">
              <el-select-v2
                v-model="form.objectName"
                :options="objectNameOptions"
                placeholder="请选择"
                class="select"
                clearable
                filterable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="组织形式" prop="orgFrom">
              <MSelect
                v-model="form.orgFrom"
                placeholder="请选择"
                :options="orgFromOptions"
                class="select"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="抽查时间" prop="spotCheckTime">
              <el-date-picker
                v-model="form.spotCheckTime"
                format="YYYY-MM-DD"
                dateFormat="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="请选择抽查时间"
                style="width: 480px"
                type="datetimerange"
                startPlaceholder="开始时间"
                endPlaceholder="结束时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="抽查事项" prop="itemNames">
              <MSelect
                v-model="form.itemNames"
                placeholder="请选择"
                :options="itemNamesOptions"
                multiple
                class="select"
                style="flex: 1"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="抽查专家" prop="operPersonNames">
              <SamplingPersonnel
                v-model="form.operPersonNames"
                class="select"
              />
            </el-form-item>
          </el-col>
          <el-form-item>
            <div style="padding-left: 20px">
              <el-button type="primary" @click="search">
                <template #icon>
                  <MIcon name="icon-search" />
                </template>
                查询
              </el-button>
              <el-button @click="reset">
                <template #icon>
                  <MIcon name="icon-refreshLeft" />
                </template>
                重置
              </el-button>
            </div>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <!--按钮-->
    <div class="btns">
      <div style="display: flex">
        <el-button
          type="primary"
          @click="AddSpotCheck(0)"
          v-if="$checkAuth('qualifiedSpotChecksAdd')"
        >
          新增
        </el-button>
        <div style="margin: 0 10px" v-if="$checkAuth('qualifiedSpotChecksDel')">
          <MDeleteButton
            @click="setInstitutionDel(selectKeys)"
            :selectKeys="selectKeys"
          ></MDeleteButton>
        </div>
        <MImportData
          :http="soptCheckImport"
          :params="{
            types: 0,
            sorgSpotCheckPlanId: params.sorgSpotCheckPlanId
          }"
          @reload="reload"
          style="margin-right: 10px"
          v-if="$checkAuth('qualifiedSpotChecksUpload')"
        ></MImportData>
        <!--<el-button> 批量导入 </el-button>-->
        <el-button
          @click="download"
          v-if="$checkAuth('qualifiedSpotChecksDownLoad')"
        >
          模板下载
        </el-button>
      </div>
      <div>
        <el-button
          @click="generatePublicPosts"
          v-if="$checkAuth('qualifiedSpotChecksGeneratePublicPosts')"
        >
          <template #icon>
            <img
              src="@/assets/imgs/spotCheck/3.svg"
              alt="icon"
              class="btn-icon"
            />
          </template>
          生成公示文章
        </el-button>
        <el-button
          @click="generateLedgers"
          v-if="$checkAuth('qualifiedSpotChecksGenerateLedgers')"
        >
          <template #icon>
            <img
              src="@/assets/imgs/spotCheck/icon/c2.svg"
              alt="icon"
              class="btn-icon"
            />
          </template>
          生成台账
        </el-button>
        <el-button
          type="primary"
          @click="setSpotCheckObjects"
          v-if="
            $checkAuth(
              'qualifiedSpotChecksIntelligentSpotCheckObjectManagement'
            )
          "
        >
          <template #icon>
            <img
              src="@/assets/imgs/spotCheck/icon/c3.svg"
              alt="icon"
              class="btn-icon"
            />
          </template>
          智能抽查对象管理
        </el-button>
      </div>
    </div>
    <!--列表-->
    <div class="list" v-loading="loading" v-if="tableData.length > 0">
      <div
        :class="it.checked ? 'list-item list-item-ac' : 'list-item'"
        v-for="it in tableData"
      >
        <div class="list-header">
          <div class="list-header-left">
            <el-checkbox v-model="it.checked" value="check" />
            <span>{{ it.objectName || '' }}</span>
          </div>
          <div class="list-header-rig">
            <MSvgIconTooltip
              name="view"
              content="查看"
              @click="toView(it.sorgSpotCheckId)"
              v-if="$checkAuth('qualifiedSpotChecksView')"
            ></MSvgIconTooltip>
            <MSvgIconTooltip
              name="edit"
              content="编辑"
              @click="AddSpotCheck(it.sorgSpotCheckId)"
              v-if="$checkAuth('qualifiedSpotChecksEdit')"
            ></MSvgIconTooltip>
            <MSvgIconTooltip
              name="thereIsAProblem"
              content="存在问题"
              @click="toProblemEntry(it.sorgSpotCheckId)"
              v-if="$checkAuth('qualifiedSpotChecksThereIsAProblem')"
            ></MSvgIconTooltip>
            <MSvgIconTooltip
              name="del"
              content="删除"
              @click="setInstitutionDel([it.sorgSpotCheckId])"
              v-if="$checkAuth('qualifiedSpotChecksDel')"
            ></MSvgIconTooltip>
          </div>
        </div>
        <div class="list-content">
          <div class="list-content-item">
            <div>
              <div class="list-content-item-label">检查事项名称</div>
              <div class="list-content-item-tx">{{ it.itemNames || '' }}</div>
            </div>
            <div>
              <div class="list-content-item-label">组织形式</div>
              <div class="list-content-item-tx">{{ it.orgFrom || '' }}</div>
            </div>
            <div>
              <div class="list-content-item-label">抽查专家</div>
              <div class="list-content-item-tx">
                {{ it.operPersonNames || '' }}
              </div>
            </div>
            <div>
              <div class="list-content-item-label">检查时间</div>
              <div class="list-content-item-tx">
                {{ getTime(it.spotCheckTime, it.spotCheckEndTime) }}
              </div>
            </div>
          </div>
          <div class="list-content-item">
            <div>
              <div class="list-content-item-label">执法检查信息</div>
              <div class="list-content-item-tx">{{ it.lawInfo || '' }}</div>
            </div>
            <div>
              <div class="list-content-item-label">发现问题</div>
              <div class="list-content-item-tx list-content-item-tx-ac">
                {{ it.problemNum || 0 }}份
              </div>
            </div>
            <div>
              <div class="list-content-item-label">整改通知</div>
              <div
                class="list-content-item-tx list-content-item-tx-ac"
                @click="previewFile(it)"
              >
                {{ it.noticeFileName || '' }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--暂无数据-->
    <div class="noData" v-else>
      <span>暂无数据</span>
      <img src="@/assets/imgs/spotCheck/noData.png" alt="" />
    </div>
    <!--分页-->
    <div class="m-table__pagination" v-if="tableData.length > 0">
      <div class="m-table__pagination__total">
        共 {{ dataTotal }} 条记录 第 {{ params.pageNum }} /
        {{ Math.ceil(dataTotal / params.pageSize) }} 页
      </div>
      <el-pagination
        background
        layout="prev, pager, next, sizes, jumper"
        v-model:currentPage="params.pageNum"
        v-model:page-size="params.pageSize"
        :total="dataTotal"
        @size-change="handleSizeChange"
        @current-change="currentChange"
      >
      </el-pagination>
    </div>
  </div>
  <!-- 抽查计划管理 -->
  <SpotCheckPlan ref="SpotCheckPlanRef" @reloadYear="reloadYear" />
  <!--新增-->
  <SpotCheck ref="SpotCheckRef" @reload="reload" />
  <!--抽查对象-->
  <SpotCheckObjects ref="spotCheckObjectsRef" @reload="reload" />
  <!--预览-->
  <MFileList ref="mfileList" :fileData="fileData" />
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import TabList from '../../components/tabList/tabList.vue'
import MSelect from '@/components/form/src/components/MSelect.vue'
import SpotCheckPlan from '../../components/spotCheckPlanManagement/spotCheckPlanManagement.vue'
import SpotCheck from '../../components/SpotCheck/SpotCheck.vue'
import SpotCheckObjects from '../../components/spotCheckObjects/spotCheckObjects.vue'
import {
  soptCheckPage,
  soptCheckDel,
  soptCheckImport,
  downloadExcelTemplate,
  sorgList,
  getManagerChild,
  soptCheckLedger,
  planPage
} from '@/api/spotCheck/spotCheck'
import { ElMessage } from 'element-plus'
import SamplingPersonnel from '@/views/spotCheck/components/samplingPersonnel/samplingPersonnel.vue'
const router = useRouter()
const route = useRoute()

defineOptions({
  name: 'SpotCheckPlan'
})

const getTime = (n, m) => {
  if (n && m) {
    return n + '至' + m
  } else if (n) {
    return n
  } else if (m) {
    return m
  } else {
    return ''
  }
}

const objectNameOptions = ref([])
const orgFromOptions = ref([])
const itemNamesOptions = ref([])
const planList = ref([])
const latestSixData = ref([])
onMounted(() => {
  sorgList().then((res) => {
    objectNameOptions.value = res.data.map((i) => ({
      value: i.orgName,
      label: i.orgName
    }))
  })
  getManagerChild('OrganizationalForm').then((res) => {
    orgFromOptions.value = res.data.map((i) => ({
      value: i.name,
      label: i.name
    }))
  })
  getManagerChild('spotCheck').then((res) => {
    itemNamesOptions.value = res.data.map((i) => ({
      value: i.name,
      label: i.name
    }))
  })

  reloadYear()
})

const reloadYear = () => {
  //年份
  planPage({ pageSize: 9999, pageNum: 1, types: 0 }).then((res) => {
    planList.value = res.data.records
    // 按照年份降序排序
    const sortedData = planList.value.sort((a, b) => b.year - a.year)
    // 取出最新年份的前6个数据 planName
    latestSixData.value = sortedData.slice(0, 6)
    params.value.sorgSpotCheckPlanId =
      latestSixData.value[0].sorgSpotCheckPlanId
    init()
  })
}

const setPlan = (id) => {
  params.value.sorgSpotCheckPlanId = id
  reload()
}
//展开
const visible = ref(false)
const setVisible = () => {
  visible.value = !visible.value
}

/*
筛选
 */
//搜索
const form = reactive({
  objectName: undefined,
  orgFrom: undefined,
  spotCheckTime: undefined,
  itemNames: undefined,
  operPersonNames: []
})
const rules = ref({
  name: [{ required: true, message: '请输入', trigger: 'blur' }]
})

const search = () => {
  let formValue = JSON.parse(JSON.stringify(form))
  params.value = {
    ...params.value,
    ...formValue,
    operPersonNames:
      form.operPersonNames.length > 0
        ? form.operPersonNames.map((i) => i.name).join(',')
        : undefined,
    itemNames:
      Array.isArray(form.itemNames) && form.itemNames.length > 0
        ? form.itemNames.join(',')
        : undefined
  }
  reload()
}

const reset = () => {
  form.objectName = undefined
  form.orgFrom = undefined
  form.spotCheckTime = undefined
  form.itemNames = undefined
  form.operPersonNames = []

  params.value = {
    ...params.value,
    ...form,
    operPersonNames:
      form.operPersonNames.length > 0
        ? form.operPersonNames.map((i) => i.name).join(',')
        : undefined
  }
  reload()
}

/*
分页
 */
const dataTotal = ref(0)
const params: any = ref({
  pageNum: 1,
  pageSize: 20,
  types: 0
})

function handleSizeChange(e) {
  params.value.pageNum = 1
  params.value.pageSize = e
  init()
}

function currentChange(e) {
  params.value.pageNum = e
  init()
}

const loading = ref(false)
const tableData = ref([])
const init = () => {
  loading.value = true
  let d = {
    ...params.value
  }
  if (params.value?.spotCheckTime) {
    d['spotCheckTime'] = params.value.spotCheckTime[0]
    d['spotCheckEndTime'] = params.value.spotCheckTime[1]
  }

  soptCheckPage(d)
    .then((res) => {
      res.data.list.forEach((i) => {
        i.checked = false
      })
      tableData.value = res.data.list
      dataTotal.value = res.data.total
    })
    .finally(() => {
      loading.value = false
    })
}

const reload = () => {
  params.value.pageNum = 1
  init()
}

//抽查计划管理
const SpotCheckPlanRef = ref()
const spotCheckPlanManagement = () => {
  SpotCheckPlanRef.value.show(0)
}

//新增抽查
const SpotCheckRef = ref()
const AddSpotCheck = (id) => {
  SpotCheckRef.value.show(id, params.value.sorgSpotCheckPlanId, 0)
}

//查看
const toView = (id) => {
  router.push({
    name: 'SpotCheckView',
    query: {
      id
    }
  })
}

//存在的问题
const toProblemEntry = (id) => {
  router.push({
    name: 'spotCheckProblemEntry',
    query: {
      id,
      status: 0,
      types: 0
    }
  })
}

//抽查对象
const spotCheckObjectsRef = ref(false)
const setSpotCheckObjects = () => {
  console.log(
    'params.value.sorgSpotCheckPlanId',
    params.value.sorgSpotCheckPlanId
  )
  spotCheckObjectsRef.value.show(params.value.sorgSpotCheckPlanId)
}

//预览
const mfileList = ref()
const fileData = ref([])
function previewFile(it) {
  let fileDataList = [
    {
      name: it.noticeFileName,
      url: it.noticeFile
    }
  ]
  fileData.value = fileDataList
  mfileList.value.detailsVisible = true
}

//选中id
const selectKeys = computed(() => {
  return tableData.value.filter((i) => i.checked).map((i) => i.sorgSpotCheckId)
})

//批量删除
const setInstitutionDel = (e) => {
  soptCheckDel({ sorgSpotCheckId: e }).then((res) => {
    ElMessage.success('删除成功！')
    reload()
  })
}

//下载模板
const download = () => {
  downloadExcelTemplate().then((res) => {
    const blob = new Blob([res], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const a = document.createElement('a')
    const URL = window.URL || window.webkitURL
    const herf = URL.createObjectURL(blob)
    a.href = herf
    a.download = '模板.xlsx'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(herf)
  })
}

//生成台账
const generateLedgers = () => {
  soptCheckLedger({
    sorgSpotCheckPlanId: params.value.sorgSpotCheckPlanId,
    types: 0
  }).then((res) => {
    const blob = new Blob([res], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const a = document.createElement('a')
    const URL = window.URL || window.webkitURL
    const herf = URL.createObjectURL(blob)
    a.href = herf
    a.download = '台账.xlsx'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(herf)
  })
}

const generatePublicPosts = () => {
  router.push({
    path: '/spotCheck/informationDisclosure',
    query: {
      sorgSpotCheckPlanId: params.value.sorgSpotCheckPlanId
    }
  })
}
</script>
<style lang="scss" scoped>
.spotCheck-content {
  width: 100%;
  min-height: 500px;
  &-search {
    width: 100%;
    box-sizing: border-box;
    padding: 20px 30px;
  }
}
.spotCheck-header-tabs {
  height: 100%;
  display: flex;
  align-items: center;
  border: 1px solid #e9e9e9;
  &-items {
    height: 100%;
    display: inline-flex;
    align-items: center;
    box-sizing: border-box;
    padding: 24px 30px;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    font-family: Source Han Sans SC, Source Han Sans SC;
    font-weight: 400;
    font-size: 18px;
    color: #666666;
    cursor: pointer;
    border-right: 1px solid #e9e9e9;
  }
  &-items:last-child {
    border-right: unset;
  }
  &-items:hover {
    font-family: Source Han Sans SC, Source Han Sans SC;
    font-weight: 500;
    font-size: 18px;
    color: #1c85ff;
    position: relative;
  }
  &-items:hover::after {
    content: '';
    width: 100%;
    height: 4px;
    background: #1c85ff;
    border-radius: 0px 0px 0px 0px;
    position: absolute;
    top: 0;
    left: 0;
  }
  &-items-ac {
    font-family: Source Han Sans SC, Source Han Sans SC;
    font-weight: 500;
    font-size: 18px;
    color: #1c85ff;
    font-weight: 500;
    position: relative;
  }
  &-items-ac::after {
    content: '';
    width: 100%;
    height: 4px;
    background: #1c85ff;
    border-radius: 0px 0px 0px 0px;
    position: absolute;
    top: 0;
    left: 0;
  }
}
.spotCheck-content-tabs {
  width: 100%;
  height: 70px;
  display: flex;
  border: 1px solid #e9e9e9;
  position: relative;
  &-content {
    flex: 1;
    height: 100%;
    box-sizing: border-box;
    padding: 0 60px;
    white-space: nowrap;
    min-width: 0;
    & > div {
      width: 100%;
    }
    & > div:last-child {
      margin-right: 0;
    }
    &-title {
      display: flex;
      align-items: center;
      font-weight: 400;
      font-size: 18px;
      color: #666666;
      padding-top: 33px;
      cursor: pointer;
      min-width: 0;
      margin-right: 80px;
      display: inline-block;
      height: 100%;
      box-sizing: border-box;
    }
    &-ac {
      font-weight: 500;
      font-size: 18px;
      color: #333333;
      position: relative;
    }
    &-ac::after {
      content: '';
      height: 4px;
      width: 60%;
      position: absolute;
      bottom: -16px;
      right: 0;
      left: 0;
      margin: auto;
      background: #1c85ff;
      border-radius: 0px 0px 0px 0px;
    }
  }
  &-rig {
    width: 200px;
    display: flex;
    justify-content: center;
    align-items: center;
    img {
      width: 26px;
      height: 26px;
      margin-right: 20px;
      cursor: pointer;
    }
  }
}
.select {
  width: 100%;
}
.btns {
  width: 100%;
  box-sizing: border-box;
  padding: 30px;
  padding-top: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.list {
  width: 100%;
  box-sizing: border-box;
  padding: 0 30px;
  .list-item {
    width: 100%;
    border-radius: 0px 0px 0px 0px;
    border: 1px solid #e9e9e9;
    padding: 0 24px;
    box-sizing: border-box;
    margin-bottom: 20px;
    .list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24px 0;
      border-bottom: 1px solid #e9e9e9;
      margin-bottom: 20px;
      .list-header-left {
        display: flex;
        align-items: center;
        span {
          font-weight: bold;
          font-size: 18px;
          color: #333333;
          margin-left: 10px;
        }
      }
      .list-header-rig {
        display: flex;
        .list-header-rig-btn {
          font-weight: 300;
          font-size: 16px;
          color: #333333;
          padding: 0 21px;
          position: relative;
          cursor: pointer;
        }
        .list-header-rig-btn::after {
          content: '';
          width: 0;
          height: 20px;
          border: 1px solid #e9e9e9;
          position: absolute;
          top: 0;
          bottom: 0;
          right: 0;
          margin: auto;
        }
        .list-header-rig-btn:last-child {
          padding-right: 0;
        }
        .list-header-rig-btn:last-child::after {
          height: 0;
        }
      }
    }
    .list-content {
      width: 100%;
      padding-bottom: 24px;
      .list-content-item {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 10px;
        & > div {
          display: flex;
          flex-wrap: wrap;
          margin-right: 120px;
          .list-content-item-label {
            font-weight: 400;
            font-size: 18px;
            color: #999999;
            margin-right: 20px;
          }
          .list-content-item-tx {
            font-weight: 400;
            font-size: 18px;
            color: #666666;
          }
          .list-content-item-tx-ac {
            font-weight: 400;
            font-size: 18px;
            color: #1763bc;
          }
        }
      }
      .list-content-item:last-child {
        margin-bottom: 0;
      }
    }
  }
  .list-item-ac {
    background: #f9fbfe;
    border-radius: 0px 0px 0px 0px;
    border: 1px solid #e2ecfc;
  }
}
.m-table__pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px 30px 30px;
  box-sizing: border-box;
  &__total {
    color: #0000006d;
  }
}
.noData {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column-reverse;
  padding: 60px 0;
  img {
    width: calc(800px / 2);
    height: calc(709px / 2);
    margin-bottom: 30px;
  }
  span {
    color: #999;
  }
}
</style>
